package util

import (
	"errors"
	"fmt"
	"io/ioutil"
	"path/filepath"
	"radar/nimrod/model"
)

// GetFileGroups return the file groups of which each contains the file with the same datetime and different elevations
func GetFileGroups(datDir string) (model.FileGroups, error) {
	if !IsExist(datDir) {
		return nil, errors.New("[ERROR] data dir does not exist")
	}

	fs, err := ioutil.ReadDir(datDir)
	if err != nil {
		return nil, fmt.Errorf("[ERROR] read dir %s", datDir)
	}

	if len(fs) == 0 {
		return nil, errors.New("[WARNING] no items in the data dir")
	}

	fileGroups := model.FileGroups{}
	fileNames := model.FileNames{}

	for _, f := range fs {
		if f.IsDir() {
			dirName := f.Name()
			if dirName != "." && dirName != ".." {
				GetFileGroups(dirName)
			}
		} else {
			fileName := f.Name()

			if len(fileNames) == 0 {
				fileNames = append(fileNames, filepath.Join(datDir, fileName))
			} else {
				// split filename to extract its datetime and elevation
				names := SplitFileName(fileName, '-', '_', '.')
				lastNames := SplitFileName(fileNames[len(fileNames)-1], '-', '_', '.')
				if names[7] == lastNames[7] && names[11] != lastNames[11] {
					// file with the same datetime and different elevation
					fileNames = append(fileNames, filepath.Join(datDir, fileName))
				} else {
					// file with different datetime
					// add the last fileNames
					fileGroups = append(fileGroups, fileNames)
					// clear fileNames
					fileNames = model.FileNames{}
					fileNames = append(fileNames, filepath.Join(datDir, fileName))
				}
			}
		}
	}
	fileGroups = append(fileGroups, fileNames)
	return fileGroups, nil
}
